﻿using System.Collections.Generic;
using System.Linq;
using ARMIR.util;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;

namespace ARMIR {
    /// <summary>
    /// 自定义的护盾装备，修改了承受伤害逻辑以及使用武器逻辑
    /// </summary>
    public class CompShield_MindShield : CompShield {
        public new CompProperties_MindShieldApparel Props => (CompProperties_MindShieldApparel)props;
        public int nextHitEffectTick;
        private bool firstCharge = false;
        private float damageRelief = 0.9f;

        public override void CompDrawWornExtras() {
            Draw();
        }
        public override void PostDraw() {
            Draw();
        }

        public override bool CompAllowVerbCast(Verb verb) {
            return true; // 允许所有武器（包括远程）
        }

        private void Break() {
            //强行击倒pawn以方便活捉小猫
            Hediff down = HediffMaker.MakeHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_catDefeat"), PawnOwner);
            PawnOwner.health.AddHediff(down);
            //来点特效
            for (int i = 0; i < 10; i++) {
                EffecterDef hit = DefDatabase<EffecterDef>.GetNamed("ARMIR_mindShield_EffecterB"); //受击效果
                hit.Spawn(PawnOwner, PawnOwner.Map);
            }
            //敌方迷迭香倒下时发出收容提醒()
            if (PawnOwner.Faction != Faction.OfPlayer) {
                ARMIR.ARMIR_language.isThatChinese(out bool yesIsIs);
                if (yesIsIs)
                {
                    string title = "迷迭香倒下了";
                    string body = "敌人的重要单位倒下了\n" +
                        "警告：该个体十分不稳定，如果想对其进行招募，请务必将其单独隔离在一个坚固的牢房\n" +
                        "并且她的意志十分坚定，不会轻易认同你的殖民地，或者说，靠言语说服她几乎是不可能的\n\n" +
                        "以及建议将其原先持有的笔记本销毁";
                    Find.LetterStack.ReceiveLetter(
                        title.Translate(), // 标题
                        body.Translate(), // 正文
                        LetterDefOf.NeutralEvent, // 信件定义
                        PawnOwner, // 可选的点击目标
                        PawnOwner.Faction // 可选的关联阵营（影响信件颜色等）
                    );
                }
                else
                {
                    string title = "Rosmontis is downed";
                    string body = "The enemy's key unit has fallen\n" +
                        "Warning: This individual is highly unstable. If you intend to recruit them, be sure to isolate them in a secure cell.\n" +
                        "And her will is very strong; she will not easily accept your colony, or rather, persuading her with words is almost impossible.\n\n" +
                        "And it is recommended to destroy the notebook originally held by them.";
                    Find.LetterStack.ReceiveLetter(
                        title.Translate(), // 标题
                        body.Translate(), // 正文
                        LetterDefOf.NeutralEvent, // 信件定义
                        PawnOwner, // 可选的点击目标
                        PawnOwner.Faction // 可选的关联阵营（影响信件颜色等）
                    );
                }
            }
            //护盾值归零及其以下时摧毁装备以移除护盾
            parent.Destroy();
        }

        public override void PostPreApplyDamage(ref DamageInfo dinfo, out bool absorbed) {
            absorbed = false;
            if (firstCharge == false) { 
                firstCharge = true;
                energy = Props.maxEnergy;
                absorbed = true;
                return;
            }
            List<DamageDef> damageDefBlacklist = new List<DamageDef>();
            if (ShieldState != ShieldState.Active || PawnOwner == null)
                return;
            EffecterDef hit = DefDatabase<EffecterDef>.GetNamed("ARMIR_mindShield_EffecterB"); //受击效果
            hit.Spawn(PawnOwner, PawnOwner.Map);
            //根据附近的盾卫数量来定值护盾强度，盾卫6人时为基准值
            if (PawnOwner.Faction != Faction.OfPlayer) {
                int shields = PawnOwner.Map.mapPawns.AllHumanlikeSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_marchInFormation"))
                && p.Faction == PawnOwner.Faction).ToList().Count;
                //计算非玩家阵营时的减伤
                if (shields <= 6)
                {
                    damageRelief = Props.damageRelief - ((6 - shields) * 0.13f);
                }
                else
                {
                    damageRelief = Props.damageRelief;
                }
            }else {
                //在玩家阵营，迷迭香周围高友方单位越多，减伤越高
                int shields = PawnOwner.Map.mapPawns.AllHumanlikeSpawned.Where(p => p.Faction == Faction.OfPlayer //玩家同阵营
                && p.Position.DistanceTo(PawnOwner.Position) < 7 //距离小于2
                && !p.HostileTo(PawnOwner) //不敌对
                && p != PawnOwner).ToList().Count; //不是自己
                if (shields <= 6)
                {
                    damageRelief = Props.damageRelief - ((6 - shields) * 0.1f);
                }
                else
                {
                    damageRelief = Props.damageRelief;
                }
            }
            damageRelief = damageRelief * (int)ARMIR_ModSettings.powerSet;
            if (damageRelief >= 1) {
                damageRelief = 0.99f;
            }

            //计算减伤
            if (dinfo.Amount / 100 * damageRelief > 0.5f) {
                energy -= 0.5f;
            }else {
                energy -= dinfo.Amount / 100 * (1 - damageRelief);
            }

            if (energy <= 0) {
                Break();
            }

            if (Find.TickManager.TicksGame > nextHitEffectTick)
            {
                nextHitEffectTick = Find.TickManager.TicksGame + 80;
            }

            absorbed = true;
            //PawnOwner 获得pawn
        }
        private void Draw()
        {
            float pct = energy / Props.maxEnergy;
            if (PawnOwner != null && pct < 1 && Find.TickManager.TicksGame < nextHitEffectTick + 2000)
            {
                Material BaseMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(1f, 1f, 1f, 0.6f));
                Material ChargeMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(0.302f, 0.941f, 0.914f, 0.8f));
                GenDraw.DrawFillableBar(new GenDraw.FillableBarRequest
                {
                    center = PawnOwner.DrawPos + Vector3.up * 1.5f + Vector3.back * 0.85f,
                    size = new Vector2(0.8f,0.2f),
                    fillPercent = pct,
                    filledMat = ChargeMat,
                    unfilledMat = BaseMat,
                    margin = 0f
                });
                Material ChargeMatRelief = SolidColorMaterials.SimpleSolidColorMaterial(new Color(1f, 1f, 1f, 0.8f));
                GenDraw.DrawFillableBar(new GenDraw.FillableBarRequest
                {
                    center = PawnOwner.DrawPos + Vector3.up * 1.5f + Vector3.back * 1f,
                    size = new Vector2(0.8f, 0.08f),
                    fillPercent = damageRelief,
                    filledMat = ChargeMatRelief,
                    unfilledMat = BaseMat,
                    margin = 0f
                });
            }
        }
    }
}